from random import Random
from utility import *
# global variable
words = json.loads(read_text("desc.json"))
random = Random()
Index = "../www/docs/.vuepress/configs/sidebar/idx.json"
Readme = "../www/docs/README.md"
ImagePath = "../www/docs/.vuepress/public/"
MdPath = "../www/docs/mds/"
# region markdown component
def lines(time:int)->str:
    return "\n"*time
def template(title:str,note:dict,ques:list[str],images:list[str])->str:
    print("in template")
    twoLines = "\n\n"
    # print("note:",note)
    # print("ques:",ques)
    # print("images:",images)
    return f"""# {note["name"]} {title.replace('_',':')}

> 检测人员:{note["name"]}
>
> 工号:{note["id"]}
>
> 项目名称:{note["proj"]}
>
> 检测地点:{note["place"]}

## 问题记录

{twoLines.join(ques)}

## 图片

{twoLines.join(images)}"""

def markdown_image(name:str,format:str,alter:str="",preffix:str='/')->str:
    return f"![{alter}]({preffix}{name}.{format})"
def make_images_group(images:list[str])->list[str]:
    oneLine=lines(1)
    return [f"### 第{idx+1}组{oneLine}{s}" for idx,s in enumerate(images)]
def make_link(name:str,link:str)->str:
    return f"- [{name}]({link})"
    # region defects
def defects_summary(count:int)->str:
    return words["summary"][2 if count > 5 else (count+4)//5]
def prob2gear(prob:float)->int:
    g = int(prob*10) - 6
    return 0 if g<0 else g
def defects_word(gear:int,count:int,type:str)->str:
    return words["desc"][gear][random.randint(0,4)].replace('$',type).replace('?',str(count))
def defects_group_content(defect:list[str])->str:
    table = {}
    result = []
    for item in defect:
        cat,prob=item.split(':')
        if cat not in table:
            table[cat] = [0,0,0,0]
        table[cat][prob2gear(float(prob))]+=1
    for key in table:
        for idx,value in enumerate(table[key]):
            if value != 0:
                result.append(defects_word(idx,value,key))
    return "\n\n".join(result)
def defects_group(seq:int,defect:list[str])->str:
    counts = len(defect)
    print("begin to join group")
    line = lines(2)
    content = defects_group_content(defect) if len(defect)!=0 else ""
    summary = defects_summary(len(defect))
    group = f"### 第{seq+1}组{line}> {summary}{line}{content}"
    print(f"group:{group}")
    return group
    # endregion
# endregion
# region file operators
def update_readme(file:str,link:str):
    content = read_text(Readme)
    content+="\n"+make_link(file,link)
    write_text(Readme,content)

def update_website():
    os.system("""cd ../www/
cp -rf docs/.vuepress/dist/* docs/.vuepress/tmp
rm html && ln -sr docs/.vuepress/tmp html
yarn docs:build
rm html && ln -sr docs/.vuepress/dist html""")
def get_image_dir(path:str)->str:
    if not os.path.exists(ImagePath):
        os.mkdir(ImagePath)
    return os.path.join(ImagePath,path)
def get_save_md(dir:str,file:str,dryrun:bool=False)->str:
    if not os.path.exists(MdPath) and not dryrun:
        os.mkdir(MdPath)
    folder = MdPath+dir
    if not os.path.exists(folder) and not dryrun:
        os.mkdir(folder)
    return folder+"/"+file+".md"
def save_index(dir:str,file:str):
    print("read index json file")
    obj = json.loads(read_text(Index))
    notFound = True
    link = f"/mds/{dir}/{file}"
    folder={
            "text":dir,
            "link":None,
            "children":[link]
        }
    print("begin to search dir")
    for d in obj["/"]:
        if dir == d["text"]:
            d["children"].append(link)
            notFound = False
            break
    if notFound:
        obj["/"].append(folder)
    write_text(Index,json.dumps(obj))
# endregion